package com.xzq.spring;

import com.xzq.core.annotation.RpcAutowire;
import com.xzq.core.annotation.RpcService;
import com.xzq.pojo.ProviderService;
import com.xzq.proxy.ProxyFactory;
import com.xzq.register.Register;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Field;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/23 11:20
 * @Version 1.0.0
 **/
public class RpcServiceFind implements BeanPostProcessor {

    private Logger logger = LoggerFactory.getLogger(RpcServiceFind.class);

    @Autowired
    private Register register;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            RpcAutowire r = field.getAnnotation(RpcAutowire.class);
            if (r != null) {
                //寻找服务
                String serviceName = field.getType().getName();
                ProviderService service = register.findService(serviceName);
                if (service != null) {
                    logger.info("服务发现：{}"+service);
                    Object proxy = ProxyFactory.getProxy(field.getType(), service.getHost(), service.getPort());
                    //将代理对象赋值给bean
                    try {
                        field.setAccessible(true);
                        field.set(bean, proxy);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return bean;
    }
}
